import 'package:flutter/material.dart';
import 'package:expandable/expandable.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/components/state_components/base_empty_component.dart';
import 'package:x3_component_core/theme/expand_theme.dart';
import 'package:x3_component_core/utils/base_component_utils.dart';

/// 设置了 dataSource 不会进行网络获取数据
class BaseRequestExpandablePanel<T> extends StatefulWidget {
  final Widget header;
  final Widget Function(dynamic) builder;
  final BaseScreenRequestModel request;
  final dynamic dataSource;
  BaseRequestExpandablePanel({Key key, @required this.header, @required this.builder, @required this.request, this.dataSource})
      : assert(builder != null),
        assert(request != null),
        super(key: key);
  @override
  _BaseRequestExpandablePanelState<T> createState() => _BaseRequestExpandablePanelState<T>();
}

class _BaseRequestExpandablePanelState<T> extends State<BaseRequestExpandablePanel> {
  final ExpandableController _controller = ExpandableController();
  Widget _secondChild;
  BaseScreenRequestModel get _request => widget.request;
  @override
  void initState() {
    _controller.addListener(() {
      if (_controller.expanded == true && _secondChild == null) {
        _onRequest();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ExpandablePanel(
      controller: _controller,
      theme: ExpandComponentsTheme.expandableThemeData,
      header: widget.header,
      expanded: AnimatedCrossFade(
        duration: Duration(milliseconds: 500),
        crossFadeState: _secondChild == null ? CrossFadeState.showFirst : CrossFadeState.showSecond,
        firstChild: Container(),
        secondChild: _secondChild == null ? BaseEmptyComponent() : _secondChild,
      ),
    );
  }

  void _onRequest() async {
    if (widget.dataSource != null) {
      _secondChild = widget.builder(widget.dataSource);
      setState(() {});
      return;
    }
    BaseComponentUtils.showLoadingDialog(context);
    BaseHttpResultModel result = await dioUtil.fetch(_request.path, method: _request.method, params: _request.params);
    BaseComponentUtils.hideLoadingDialog(context);
    if (result.success == true) {
      dynamic data = result.data;
      if (data is T) {
        _secondChild = widget.builder(data);
      }
      setState(() {});
    }
  }
}
